package com.example.springsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springsecurity.domain.LoginUser;
import com.example.springsecurity.domain.SysUser;
import com.example.springsecurity.mapper.SysUserMapper;
import com.example.springsecurity.service.SysUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        SysUser user=sysUserMapper.selectOne(queryWrapper);
        //如果user为空就抛出异常
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 权限信息  要从数据库里查
        List<String> perms = sysUserMapper.findPermsByUserId(user.getId());

        //TODO 根据用户查询权限信息 添加到LoginUser中
//        List<String> list = new ArrayList<>(Arrays.asList("test"));
        //把数据封装成UserDetails返回
        return new LoginUser(user,perms);
    }
}
















